﻿using Autofac;
using RxxApi.IServices.BASE;
using RxxApi.Repository.BASE;
using RxxApi.Repository.UnitOfWorks;
using RxxApi.Services.BASE;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace RxxApi.Extensions.ServiceExtensions;

public class AutofacSetup : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        var basePath = AppContext.BaseDirectory;
        var servicesDllFile = Path.Combine(basePath, "RxxApi.Services.dll");
        var repositoryDllFile = Path.Combine(basePath, "RxxApi.Repository.dll");
        builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>))
           .InstancePerDependency(); //注册仓储
        builder.RegisterGeneric(typeof(BaseServices<>)).As(typeof(IBaseServices<>))
           .InstancePerDependency(); //注册服务
        // 获取 Service.dll 程序集服务，并注册
        var assemblysServices = Assembly.LoadFrom(servicesDllFile);
        builder.RegisterAssemblyTypes(assemblysServices)
            .AsImplementedInterfaces()
            .InstancePerDependency()
            .PropertiesAutowired();
        // 获取 Repository.dll 程序集服务，并注册
        var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
        builder.RegisterAssemblyTypes(assemblysRepository)
            .AsImplementedInterfaces()
            .PropertiesAutowired()
            .InstancePerDependency();

        builder.RegisterType<UnitOfWorkManage>().As<IUnitOfWorkManage>()
               .AsImplementedInterfaces()
               .InstancePerLifetimeScope()
               .PropertiesAutowired();
    }
}
